# -*- coding: utf-8 -*-

"""
Module implementing MyMainWindow.
"""

'''
功能：点击一下按键产生一个随机数据
x坐标随着数据增多自动变化最大值
'''

import sys, time
from PyQt5.QtWidgets import QMainWindow
from Ui_matplotPyqt5 import Ui_MainWindow  # 生成的这个前面的.   要去掉

# 自己加的
from PyQt5 import QtCore, QtWidgets
# 导入matplotlib模块并使用Qt5Agg
import matplotlib

matplotlib.use('Qt5Agg')
# 使用 matplotlib中的FigureCanvas (在使用 Qt5 Backends中 FigureCanvas继承自QtWidgets.QWidget)
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
import matplotlib.pyplot as plt
import numpy as np
from numpy import *
from matplotlib.figure import Figure

from mpl_toolkits.mplot3d import Axes3D
from matplotlib.lines import Line2D
import matplotlib.cbook as cbook
from PyQt5.QtWidgets import QApplication, QMainWindow, QGridLayout
from PyQt5.QtCore import QTimer

# 为了显示中文
# 如果是在 PyCharm 里，只要下面一行，上面的一行可以删除
plt.rcParams['font.sans-serif'] = ['SimHei']
# 用来正常显示负号
plt.rcParams['axes.unicode_minus'] = False

# 定义了存储想要存储的压力数据的array
sensorDataType = np.dtype([('A0', 'i4'), ('A1', 'i4'), ('A2', 'i4'), ('A3', 'i4'), ('A4', 'i4'), ('A5', 'i4'),
                           ('A6', 'i4'), ('A7', 'i4'), ('A8', 'i4'), ('A9', 'i4'), ('A10', 'i4'),
                           ('A11', 'i4')])
# pressPoint = np.array((1,2,3,4,5,6,7,8,9,10,11,12),dtype=sensorDataType)
# print(pressPoint['A0'])
pressPointsType = np.dtype([('sensorDatas', sensorDataType), ('nums', 'i4'), ('times', 'S20')])


class MyMainWindow(QMainWindow, Ui_MainWindow):
    """
    Class documentation goes here.
    """

    def __init__(self, parent=None):
        """
        Constructor
        
        @param parent reference to the parent widget
        @type QWidget
        """
        super(MyMainWindow, self).__init__(parent)
        self.setupUi(self)

        self.xlim = 10  # 初始化x轴的最大值是10
        self.countPoint = 0  # 用于记录保存了多少组数据
        self.pressPoints = np.array([((0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), 0, '00:00:00')],
                                    dtype=pressPointsType)

        self.Init_Widgets()
        self.timer = QTimer()
        self.timer.start(100)
        self.ts = time.time()
        # self.timer.timeout.connect(self.UpdateImgs)
        self.pushButton.clicked.connect(self.addData)

        # 点击下拉菜单action
        self.actionShop.triggered.connect(self.gotoShopUrl)



    def addData(self):
        print('button')

        # 测试插入数据
        self.countPoint = self.countPoint + 1
        addPoint = np.array(
            [((random.randint(0, 10000), 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12), self.countPoint, '00:00:00')],
            dtype=pressPointsType)
        self.pressPoints = np.append(self.pressPoints, addPoint, axis=None)
        # print(pressPoints)

        self.x = self.pressPoints['nums']
        print(self.x)
        self.y = self.pressPoints['sensorDatas']['A0']
        print(self.y)
        self.line.set_xdata(self.x)
        self.line.set_ydata(self.y)

        self.line.set_label("A0")

        if (self.countPoint > self.xlim):
            self.xlim = self.countPoint
            self.LineFigure.ax.set_xlim(0, self.xlim)
        self.LineFigure.draw()

    def UpdateImgs(self):
        dt = time.time() - self.ts
        print(dt)
        self.LineUpdate(dt)

    def LineUpdate(self, dt):
        y = 3000 * np.sin(self.x + dt) + 5000
        # y = [random.randint(0, 10000) for i in range(60)]
        self.line.set_ydata(y)
        # self.line.set_label("A0")
        self.LineFigure.draw()

    def Init_Widgets(self):
        self.PrepareSamples()
        self.PrepareLineCanvas()

    def PrepareSamples(self):
        self.x = [0]
        self.y = [0]

    def PrepareLineCanvas(self):
        self.LineFigure = Figure_Canvas()
        self.LineFigureLayout = QGridLayout(self.lineDisplayGB)
        self.LineFigureLayout.addWidget(self.LineFigure)
        self.LineFigure.ax.set_xlim(0, self.xlim)
        self.LineFigure.ax.set_ylim(0, 10000)
        # Line2D函数使用方法
        # https://my.oschina.net/u/3473376/blog/895310
        # https://www.jianshu.com/p/4a6565891faf
        # https://matplotlib.org/api/_as_gen/matplotlib.lines.Line2D.html#matplotlib.lines.Line2D
        self.line = Line2D(self.x, self.y, color='r', marker='o')
        self.LineFigure.ax.add_line(self.line)
        self.LineFigure.ax.set_xlabel('时间（s）')
        self.LineFigure.ax.set_ylabel('压力（g）')
        self.LineFigure.ax.set_title('压力@时间曲线')
        self.LineFigure.ax.legend([self.line],['A0'])      #显示出来标签

    def gotoShopUrl(self):
        import webbrowser
        webbrowser.open("https://ilovemcu.taobao.com")


class Figure_Canvas(FigureCanvas):
    def __init__(self, parent=None, width=3.9, height=2.7, dpi=100):
        self.fig = Figure(figsize=(width, height), dpi=100)
        super(Figure_Canvas, self).__init__(self.fig)
        self.ax = self.fig.add_subplot(111)

    def test(self):
        x = [1, 2, 3, 4, 5, 6, 7]
        y = [2, 1, 3, 5, 6, 4, 3]
        self.ax.plot(x, y)


if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    myshow = MyMainWindow()
    myshow.show()
    sys.exit(app.exec_())
